package ChatApp.ClietnPart;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * Created with IntelliJ IDEA.
 * User: Zuxs
 * Date: 4.09.12
 * Time: 21:35
 * To change this template use File | Settings | File Templates.
 */
public class Client {
    int port = 6666;
    Socket reqsoket;
    ObjectInputStream inputStream;
    ObjectOutputStream outputStream;
    String message;
    public static String username;
    Client() {};

    void runChater() {
        try {
            reqsoket = new Socket("localhost", port);
            System.out.println("Connected to localhost");
            outputStream = new ObjectOutputStream(reqsoket.getOutputStream());
            outputStream.flush();
            inputStream = new ObjectInputStream(reqsoket.getInputStream());
            do {
                try {
                    message = (String) inputStream.readObject();

                    String[] msg = message.split(":");
                    System.out.println(msg[1] + " > " + msg[0]);
                    int i = 0;
                   if(message.equals("Test done"))  {
                    sendmessage("Nice");
                   }
                   else{
                       while (i < 10) {
                           sendmessage(i + " Ohoy");
                           i++;
                       }
                       sendmessage("done");
                   }
                } catch (ClassNotFoundException e) {
                    System.out.println(e);
                }
            } while (!message.equals("bye"));
        } catch (UnknownHostException e) {
            System.err.println("Server uknown");
        } catch (IOException e) {
            System.out.println(e);
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    void sendmessage(String message) {
        try {
            String msg = message +":"+username;
            outputStream.writeObject(msg);
            outputStream.flush();
            System.out.println(username + " > " + msg);
        } catch (IOException e) {
            System.out.println(e);
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    public static void main(String[] args) {
        Client chater = new Client();
        username = args[0];
        chater.runChater();
    }

}
